/*
 * @LastEditTime: 2024-03-14 15:44:25
 * @Description: 封装 storage类
 */
import config from '@/config';

const { appName } = config;

if (import.meta.env.ENV === 'development') {
	sessionStorage.setItem('storageIsolation', '0');
}

/**
 * @description: 获得缓存的前缀
 *               默认为 appName_，开启隔离后变为 NODE_ENV_appName_
 *               子应用中，特殊参数直接使用主应用的前缀，这样能取到主应用缓存的数据
 *
 */
export function getStoragePrefix() {
	let IsolationPrefix = sessionStorage.getItem('storageIsolation') ? '' : `${import.meta.env.ENV}_`;
	return `${IsolationPrefix}${appName}_`;
	// return '';
}

export default {
	/**
	 * @description: localStorage存储封装
	 * @param {String} name
	 * @param {String} value
	 * @return: void
	 */
	set: (name, value) => {
		localStorage.setItem(`${getStoragePrefix(name)}${name}`, value);
	},

	/**
	 * @description: localStorage获取封装
	 * @param {String} name
	 * @return: String
	 */
	get: (name) => {
		return localStorage.getItem(`${getStoragePrefix(name)}${name}`);
	},

	/**
	 * @description: localStorage移除封装
	 * @param {String} name
	 * @return: void
	 */
	remove: (name) => {
		localStorage.removeItem(`${getStoragePrefix(name)}${name}`);
	},

	/**
	 * @description: localStorage清空封装
	 * @param {String} name
	 * @return: String
	 */
	clear: () => {
		let len = localStorage.length;
		let keys = [];

		for (let i = 0; i < len; i++) {
			let key = localStorage.key(i);
			if (key && key.startsWith(getStoragePrefix())) {
				keys.push(key);
			}
		}

		keys.map((key) => localStorage.removeItem(key));
	}
};
